<?php
// +----------------------------------------------------------------------
// | OpenCMF [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.opencmf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 狂奔的小白兔  1194174530@qq.com
// +----------------------------------------------------------------------
namespace Sport\Model;
use Think\Model;
/**
 * 学院模型
 * @author 狂奔的小白兔  1194174530@qq.com
 */
class AcademyModel extends Model {
    /**
     * 数据库表名
     * @author 狂奔的小白兔  1194174530@qq.com
     */
    protected $tableName = 'sport_academy';

    /**
     * 自动验证规则
     * @author 狂奔的小白兔  1194174530@qq.com
     */
    protected $_validate = array(
        // 验证学院名称
        array('academy', 'require', '请填写学院名称', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('academy', '3,32', '学院名称长度为1-32个字符', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
        array('academy', '', '学院名称被占用', self::MUST_VALIDATE, 'unique', self::MODEL_BOTH),
    );

    /**
     * 自动完成规则
     * @author 狂奔的小白兔  1194174530@qq.com
     */
    protected $_auto = array(
        array('cheer', '0', self::MODEL_BOTH),
        array('sort', '0', self::MODEL_BOTH),
        array('create_time', 'time', self::MODEL_BOTH, 'function'),
        array('status', '1', self::MODEL_BOTH),
    );

        /**
     * 查找后置操作
     * @author jry <598821125@qq.com>
     */
    protected function _after_find(&$result, $options) {
       if ($result['cid']) {
           $result['category_info'] = D($this->moduleName.'/Category')->find($result['cid']);
       }
    }

    /**
     * 查找后置操作
     * @author jry <598821125@qq.com>
     */
    protected function _after_select(&$result, $options) {
        foreach($result as &$record){
            $this->_after_find($record, $options);
        }
    }

        /**
     * 获取导航树，指定导航则返回指定导航的子导航树，不指定则返回所有导航树，指定导航若无子导航则返回同级导航
     * @param  integer $id    导航ID
     * @param  boolean $field 查询字段
     * @return array          导航树
     * @author jry <598821125@qq.com>
     */
    public function getNavTree($id = 0, $group = 'main', $field = true) {
        // 获取当前导航信息
        if ((int)$id > 0) {
            $info = $this->find($id);
            $id   = $info['id'];
        }
        // 获取所有导航
        $map['status'] = array('eq', 1);
        $map['group']  = array('eq', $group);
        $tree = new Tree();
        $list = $this->field($field)->where($map)->order('sort asc,id asc')->select();

        // 返回当前导航的子导航树
        $list = $tree->list_to_tree(
            $list,
            $pk = 'id',
            $pid = 'pid',
            $child = '_child',
            $root = (int)$id
        );
        if (!$list) {
            return $this->getSameLevelNavTree($id);
        }
        return $list;
    }

}
